package com.onlineshopping.service.impl;

import com.onlineshopping.entity.User;
import com.onlineshopping.mapper.UserMapper;
import com.onlineshopping.service.MailService;
import com.onlineshopping.vo.UserVo;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Random;

/**
 * @author laisir
 * @date 2024/9/5
 */
@Service
@RequiredArgsConstructor
public class MailServiceImpl implements MailService {

    private static final Logger log = LoggerFactory.getLogger(MailServiceImpl.class);
    private final UserMapper userMapper;
    @Value("${spring.mail.username}")
    private String from;
    private final JavaMailSender mailSender;

    @Override
    public boolean sendMail(String to, HttpSession session) {
        try {
            //log.info("Session ID: {}", session.getId());
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            // 生成随机数
            String code = randomCode();
            // 设置邮件内容
            // 将随机数放置到session中
            session.setAttribute("email", to);
            session.setAttribute("code", code);
            // 60秒后过期
            session.setAttribute("expiration", System.currentTimeMillis() + 60000);

            simpleMailMessage.setSubject("验证码邮件"); // 主题
            simpleMailMessage.setText("您注册或重置密码所需的验证码是：" + code + ", 验证码有效期为60s"); // 内容
            simpleMailMessage.setFrom(from); // 发件人
            simpleMailMessage.setTo(to); // 收件人
            mailSender.send(simpleMailMessage); // 发送
            return true;
        } catch (Exception e) {
            log.error("发送邮件失败", e);
            return false;
        }
    }

    /**
     * 生成随机验证码 6位数字
     * @return 验证码
     */
    @Override
    public String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for(int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }

    @Override
    public boolean register(UserVo userVo, HttpSession session) {
        //log.info("Session ID: {}", session.getId());
        // 获取session中的验证信息
        String email = (String) session.getAttribute("email");
        String code = (String) session.getAttribute("code");
        //System.out.println("email:" + email + " code:" + code);

        Long captchaExpiry = (Long) session.getAttribute("expiration");

        // 检查验证码是否存在且未过期
        if (code == null || captchaExpiry == null || System.currentTimeMillis() > captchaExpiry) {
            log.error("验证码不存在或已过期");
            return false;
        }

        // 获取表单中的提交的验证信息
        String voCode =  userVo.getCode();
        //System.out.println("voCode:" + voCode);

        //如果email数据为空 或者 code不一致都失败
        if (email == null || email.isEmpty()) {
            log.error("email为空");
            return false;
        } else if (!code.equals(voCode)){
            log.error("验证码不一致");
            return false;
        }
        // 保存数据
        User user = userVo.toUser();
        // 将数据写进数据库
        userMapper.insertUser(user);
        // 跳转成功页面
        return true;
    }
}
